package com.leixin.demo.service.impl;

import com.leixin.demo.dao.UrlDao;
import com.leixin.demo.entity.UrlEntity;
import com.leixin.demo.service.UrlService;
import com.leixin.demo.utlis.JsoupHelper;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class UrlServiceImpl implements UrlService {
    @Autowired
    UrlDao urlDao;

    public void getURLInfo(String urlInfo, Integer page) throws Exception {
        // System.setProperty("proxySet", "true");
        // System.setProperty("socksProxyHost","127.0.0.1");
        // System.setProperty("socksProxyPort","8787");
        // System.setProperty("http.proxySet", "true");
        // System.setProperty("http.proxyHost", "127.0.0.1");
        // System.setProperty("http.proxyPort", "8787");
        URL url = new URL(urlInfo);
        HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
        if (httpUrl.getResponseCode() == 200) {
            InputStream is = httpUrl.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            Pattern p = Pattern.compile("<a\\b[^>]+\\bhref=\"([^\"]*)\"[^>]*>([\\s\\S]*?)</a>");
            String[] split = sb.toString().split("上一页");
            String[] split2 = split[0].toString().split("<tr bgcolor=\"#F5FAFE\">");
            String[] remove = ArrayUtils.remove(split2, 0);
            for (String s : remove) {
                Matcher matcher = p.matcher(s);
                if (matcher.find(0)) {
                    String urlname = "http://www.bibizyz8.com";
                    UrlEntity urlmodel = new UrlEntity();
                    urlmodel.setName(matcher.group(2));
                    String avi = urlname + matcher.group(1);
                    urlmodel.setUrl(avi);
                    urlmodel.setUrlimg(getimg(avi));
                    List<String> listAvi = getAvi(avi);
                    for (String address : listAvi) {
                        urlmodel.setUrlavi(address);
                        urlDao.insert(urlmodel);
                        System.out.println(Thread.currentThread().getName() + ":  " + urlmodel.toString());
                    }
                }
            }
            is.close();
            br.close();
        }
        System.out.println(Thread.currentThread().getName() + "   :网站链接失败");
    }

    public List<UrlEntity> selectname(UrlEntity url) {
        return urlDao.selectname(url);
    }

    public List<UrlEntity> selectall() {
        return urlDao.selectall();
    }

    public List<String> getAvi(String avi) throws Exception {
        JsoupHelper jsoupHelper = new JsoupHelper();
        List<String> img = jsoupHelper.fecthAttr(avi, "/html/body/div[6]/table[2]/tbody/tr[3]/td/ul/li/input", "value");
        return img;
    }

    public String getimg(String avi) throws Exception {
        JsoupHelper jsoupHelper = new JsoupHelper();
        List<String> img = jsoupHelper.fecthAttr(avi, "/html/body/table[2]/tbody/tr/td/div/img", "src");
        if (img.size() > 0) {
            return img.get(0);
        }
        img = jsoupHelper.fecthAttr(avi, "/html/body/table[2]/tbody/tr/td/img", "src");
        if (img.size() > 0) {
            return img.get(0);
        }
        return "没有图片存在";
    }

    @Override
    public void pathImg(String path) throws Exception {
        List<UrlEntity> list = urlDao.selectall();
        for (UrlEntity var : list) {
            URL url = new URL(var.getUrlimg());
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            String imageName = path +"//"+ var.getId()+".jpg";
            FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            byte[] context = output.toByteArray();
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
            System.out.println("图片下载完成,请在" + path + "查看");
        }
    }
}
